<template>
    <view class="d-kuan">
        <uv-overlay :show="yinpin_data_show" @tap="yinpin_close_get" zIndex="998" opacity="0.5">
        <view class="warp_yinpin">
            <view class="rect_yinpin" @tap.stop.prevent>
                <view class="d-kuan ">
                    <view class="d-kuan d-zhuangtai d-yinpin-gao">
                        <view class="d-kuan d-zhuangtai-left">
                            <uv-cell icon="mic" title="音频详情"></uv-cell>
                        </view>
                        <uv-form  ref="form">
                            <NlAudioPlayer
                                ref="audioPlayer"
                                v-if="yinpin_data_add && yinpin_data_add.yinpin && yinpin_data_add.yinpin.length > 0"
                            	:src="yinpin_data_add && yinpin_data_add.yinpin && yinpin_data_add.yinpin[0]"
                            	style="margin: 20px 0;"
                            	:bar-bg-style="{ borderRadius: '50px' }"
                            	:bar-style="{ backgroundColor: '#27a393', borderRadius: '50px' }"
                            	:dot-style="{ width: '30rpx', height: '30rpx', backgroundColor: '#2ebdac' }"
                            ></NlAudioPlayer>
                        </uv-form>
                        <view class="d-kuan d-clear"></view>
                        <view class="d-kuan d-shang-10" style="display: flex; justify-content: center; align-items: center;">
                            <uv-upload
                            	:fileList="fileList_yinpin1"
                            	name="1"
                            	multiple
                            	leixing="3"
                            	:maxCount="1"
                            	@afterRead="afterRead_yinpin"
                            	@delete="delete_yinpin"
                            	accept="audio/*"
                            	:previewFullImage="true"
                            	width="50"
                            	height="50"
                            	fileType="audio"
                            ></uv-upload>
						
                        </view>
                        <uv-button v-if="yinpin_data_add && yinpin_data_add.yinpin && yinpin_data_add.yinpin.length > 0" class="d-shang-10" type="primary" text="修改" @click="postYinpin_data_xiugai_api"></uv-button>
                        <uv-button v-else class="d-shang-10 " type="primary" text="添加音频" @click="postYinpin_data_xiugai_api" ></uv-button>
                        
                    </view>
                </view>
            </view>
        </view>
    </uv-overlay>
    </view>
</template>

<script>
    import Api from '@/utils/api.js';
    import QuanApi from '@/utils/quan_api.js';
    import NlAudioPlayer from '@/uni_modules/nl-audio-player/components/nl-audio-player/nl-audio-player.vue'
	import { getRequest,postRequest } from '@/utils/wxRequest.js';
export default {
    props: {
        yinpin_data_show: {
            type: Boolean,
            default: false
        },
        yinpin_data_list: {
            type: [Array, Object], // 支持数组或对象类型
            default: () => []
        },
        tieid: {
            type: [String, Number],
            default: 0
        },
        quanid: {
            type: [String, Number], // 支持字符串或数字类型
            default: 0
        },
    },
    components: {
        NlAudioPlayer
    },
	data() {
		return {
			yinpin_data_add:{},
			yinpin_data_list_cuozuo: 0,
			fabuid:{},//发布id
            fileList1: [],//音频存储
            fileList_yinpin1: [],//音频存储
            fabuid_yinpin:{},//发布id
            up_yinpin:[],
		}
	},
	watch: {
		// 监听yinpin_data_list变化，有数据时传递给yinpin_data_add并更新操作状态
		yinpin_data_list: {
				handler(newVal) {
					//console.log('yinpin_data_list变化:', newVal);
					if (newVal && newVal.length > 0) {
						// 深拷贝数据到yinpin_data_add
						var list = JSON.parse(JSON.stringify(newVal[0]));
                        //console.log('传入数据:',list);
                    this.yinpin_data_add = list;
                    //console.log('yinpin_data_add更新后:', this.yinpin_data_add);
                    // 有数据时设置操作为修改模式
                    this.yinpin_data_list_cuozuo = 1;
					} else {
						//console.log('yinpin_data_list为空');
						// 没有数据时设置操作为添加模式
                    this.yinpin_data_list_cuozuo = 0;
					}
				},
				deep: true,
				immediate: true // 立即执行一次
			},
		// 监听弹出组件显示，触发获取发布ID和数据同步
		yinpin_data_show: {
				handler(newVal) {
					//console.log('yinpin_data_show变化:', newVal);
					if (newVal) {
						this.getFabuid_api();
						// 组件显示时，再次同步数据
						this.syncYinpinData();
					}
				},
				immediate: false
			}
	},
	methods: {
		// 音频列表
		yinpin_data_cunzai_api(){
			this.$refs.Dyinpin_data.yinpin_data_cunzai_api();
		},
		// 同步音频数据
		syncYinpinData() {
			//console.log('开始同步音频数据');
			//console.log('当前yinpin_data_list:', this.yinpin_data_list);
			if (this.yinpin_data_list) {
				// 深拷贝数据到yinpin_data_add
				var list = JSON.parse(JSON.stringify(this.yinpin_data_list));
				//console.log('同步的音频数据:', list);
				this.yinpin_data_add = list;
				//console.log('同步后yinpin_data_add:', this.yinpin_data_add);
				// 设置为修改模式
				this.yinpin_data_list_cuozuo = 1;
			} else {
				//console.log('没有可同步的音频数据');
				// 设置为添加模式
				this.yinpin_data_list_cuozuo = 0;
			}
		},
        // 关闭音频列表
        yinpin_close_get(){
            // 停止音频播放
            if (this.$refs.audioPlayer) {
                try {
                    this.$refs.audioPlayer.pause();
                } catch (error) {
                    //console.log('停止音频播放失败:', error);
                }
            }
            this.$emit('yinpin_close_get', false);
            // 保留音频数据，避免下次打开时需要重新加载
            //console.log('关闭组件时保留音频数据');
        },
        // 上传音频
		yinpin_upload(){
            const duixin = this; // 定义duixin变量指向this
            const uid = this.$store.state.memberuid;
            const keycode = this.$store.state.keycode;
            
            if(!uid || !keycode){
                uni.showToast({
                    icon: 'none',
                    title: '请先登录'
                });
                return;
            }
            
            uni.chooseAudio({
                success: (res) => {
                    // 显示加载中
                    uni.showLoading({
                        title: '上传中...'
                    });
                    var upid = duixin.fabuid && duixin.fabuid.yinpinid;
                    // 使用uni.uploadFile上传音频文件
                    uni.uploadFile({
                        url: QuanApi.postTupians(uid,keycode)+'&fid='+upid,
                        filePath: res.tempFilePath,
                        name: 'file_data',
                        formData: {
                            is_ajax: 1
                        },
                        success: (uploadRes) => {
                            try {
                                const data = JSON.parse(uploadRes.data);
                                if(data.code){
                                    // 上传成功，保存返回的音频URL为数组格式
                                    const yinpinUrl = data.data.url || '';
                                    // 确保yinpin_data_add存在并且有yinpin数组
                                    if (!duixin.yinpin_data_add) {
                                        duixin.yinpin_data_add = {};
                                    }
                                    if (!duixin.yinpin_data_add.yinpin) {
                                        duixin.yinpin_data_add.yinpin = [];
                                    }
                                    duixin.yinpin_data_add.yinpin[0] = yinpinUrl;
                                    
                                    uni.showToast({
                                        icon: 'success',
                                        title: '上传成功'
                                    });
                                } else {
                                    uni.showToast({
                                        icon: 'none',
                                        title: data.msg || '上传失败'
                                    });
                                }
                            } catch (error) {
                                uni.showToast({
                                    icon: 'none',
                                    title: '上传失败，请重试'
                                });
                            }
                        },
                        fail: (error) => {
                            //console.log('上传失败:', error);
                            uni.showToast({
                                icon: 'none',
                                title: '上传失败，请重试'
                            });
                        },
                        complete: () => {
                            uni.hideLoading();
                        }
                    });
                },
                fail: (error) => {
                    //console.log('选择音频失败:', error);
                }
            });
        },
        // 音频上传
		async afterRead_yinpin(event) {
			const duixin = this; // 定义duixin变量指向this
			// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
				//console.log('event',event); 
				let lists = [].concat(event.file)
				let fileListLen = this[`fileList_yinpin${event.name}`].length || 0;

				lists.map((item) => {
					// 确保item.type存在，设置默认值
					const fileType = item.type || 'audio/mpeg';
                    this[`fileList_yinpin${event.name}`].push({
                    	...item,
                    	status: 'uploading',
                    	message: '上传中',
                    	type: fileType,
                    	// 显式设置fileType为audio，避免组件误判
                    	fileType: 'audio',
                    	// 确保url属性始终存在，避免传递undefined给image()函数
                    	url: item.url || item.path || '',
                    	// 确保thumb属性始终存在
                    	thumb: item.thumb || item.url || item.path || ''
                    })
                    
				})
			for (let i = 0; i < lists.length; i++) {
				try {
					const result = await this.uploadFilePromise(lists[i].url, 2)
					// 安全地获取id，防止中间属性不存在
					const id = duixin.up_yinpin && duixin.up_yinpin.data && duixin.up_yinpin.data.id || 0;
					
					let item = this[`fileList_yinpin${event.name}`][fileListLen]
					// 更新文件列表状态
						const updatedItem = Object.assign({}, item, {
							status: 'success',
							message: '',
							url: result || '',
							id: id
						})
						this[`fileList_yinpin${event.name}`].splice(fileListLen, 1, updatedItem)
						fileListLen++
				} catch (error) {
					//console.error('处理音频文件时出错:', error);
					// 可以考虑添加错误提示
				}
				// 注释掉自动插入逻辑，根据用户需求取消自动插入
				// if (updatedItem.fileType === 'image') {
				// 	this.handleInsertImage({ url: result })
				// } else if (updatedItem.fileType === 'video') {
				// 	this.handleInsertVideo({ url: result })
				// }
				}
		},
		// 删除视频
		delete_yinpin(event) {
			this[`fileList_yinpin${event.name}`].splice(event.index, 1)
		},
        		//上传图片
		uploadFilePromise(url,leixing) {
			
			
			var duixin = this; 
			const uid = this.$store.state.memberuid;
            const keycode = this.$store.state.keycode;
            var upid = duixin.fabuid && duixin.fabuid.yinpinid;
            if(this.yinpin_data_add && this.yinpin_data_add.yinpin && this.yinpin_data_add.yinpin.length){
                this.$refs.audioPlayer.pause();
            }
            
            this.yinpin_data_add.yinpin = [];
			return new Promise((resolve, reject) => {
				let a = uni.uploadFile({
					url: Api.postTupians(uid,keycode)+'&fid='+upid, //
					filePath: url,
					name: 'file_data',
					formData: {
						is_ajax:1
					},
					success: (res) => {
						var duixin = this; 
                        duixin.up_yinpin = JSON.parse(res.data);
                        //打印duixin.uptu
                        //console.log('duixin.up_yinpin',duixin.up_yinpin);
                        const yinpinUrl = duixin.up_yinpin.data.url || '';
                        //上传成功后，返回音频url给 yinpin_data_add && yinpin_data_add.yinpin[0]
                        //console.log('服务器返回的音频URL:', yinpinUrl);
                        // 检查yinpin_data_add是否存在
                        
                        if (this.yinpin_data_add) {
                        	// 确保yinpin属性存在并且是数组
                        	if (!this.yinpin_data_add.yinpin) {
                        		this.yinpin_data_add.yinpin = [];
                        	}
                        	// 将音频URL赋值给yinpin数组的第一个元素
                        	this.yinpin_data_add.yinpin[0] = yinpinUrl;
                        } else {
                        	// 如果yinpin_data_add不存在，创建一个新对象
                        	this.yinpin_data_add = { yinpin: [yinpinUrl] };
                        }
                        setTimeout(() => {
                        	resolve(yinpinUrl)
                        }, 1000)
						}
						
				});
			})
		},
        //发布id
        getFabuid_api(){
        	var duixin = this; 
        	var get_data = getRequest(Api.getFabuid());
        		var res;
        		get_data.then(duixin_data => {
        			res = duixin_data;
        			if(res.data.code) {
        				duixin.fabuid = res.data.data;
        			} else {
        				uni.showToast({
        					icon: 'none',
        					title: '获取失败，请稍后重试'
        				});
        			}
        		})
        },
        //修改
		postYinpin_data_xiugai_api(){
				// 确保从 Vuex 获取最新值
				const uid = this.$store.state.memberuid;
                const keycode = this.$store.state.keycode;
                // 确保id存在
                const id = this.tieid || 0;
                
				// 上传音频
				let yinpin = '';
				var up_yinpin =this.fileList_yinpin1;
				up_yinpin.forEach(item=>{
					yinpin+= '&data[yinpin][id][]='+item.id+'&data[yinpin][title][]=yinpin'
				})
			var datas = "is_ajax=1&cid="+id+yinpin;
			var post_data = postRequest(QuanApi.getEdit_yinpin(uid,keycode,id),datas);
			var res;
			post_data.then(duixin_data => {
				res = duixin_data;
				if(res.data.code) {
					uni.showToast({
						icon: 'none',
						title: res.data.msg
					});
                    //修改成功后，刷新父组件帖子数据
                    this.$emit('refreshData');
					// 操作成功后关闭组件
					this.yinpin_close_get();
				} else {
					uni.showToast({
						icon: 'none',
						title: '修改失败'
					});
				}
			})

			
		}
	}
}
</script>

<style>
.warp_yinpin {
	display: flex;
	align-items: center;
	justify-content: center;
	height: 100%;
}
.rect_yinpin {
	width: 300px;
	/*height: 300px;*/
	padding: 10px;
	background-color: #fff;
	border-radius: 10px;
}
.d-yinpin-gao {
    /*height: 500rpx;*/
    overflow: auto;
}
</style>